package com.huajin.codetest.thread.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 线程池
 *
 * @author hongwei.lian
 * @date 2022年11月26日 下午6:31:09
 */
public class InvokeAllTest {

    private static ExecutorService THREAD_POOL_EXECUTOR = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors() + 1);

    public static void main(String[] args) throws Exception {
        List<Callable<Integer>> tasks = getCallables();
        long start = System.currentTimeMillis();
        List<Future<Integer>> futures = THREAD_POOL_EXECUTOR.invokeAll(tasks, 300, TimeUnit.MILLISECONDS);
        for (Future<Integer> future : futures) {
            if (future.isCancelled()) {
                System.out.println("超时了");
            } else {
                Integer integer = future.get();
                System.out.println("正常的结果-->" + integer);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时" + (end - start));
        System.in.read();
    }

    private static List<Callable<Integer>> getCallables() {
        List<Callable<Integer>> tasks = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            tasks.add(new InvokeAllThread1());
        }
        for (int i = 0; i < 3; i++) {
            tasks.add(new InvokeAllThread2());
        }
        return tasks;
    }

    public static class InvokeAllThread1 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("InvokeAllThread1");
            return 1;
        }
    }

    public static class InvokeAllThread2 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("InvokeAllThread2");
            return 2;
        }
    }
    
}